package com.xxl.job.executor.service.jobhandler;

/**
 * @author Zjl
 * @description TODO
 * @since 2025/3/27 19:15
 */

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DbUtil;
import com.alibaba.fastjson2.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.Date;

@Component
public class QueryXxlJob {
    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("queryJobHandler")
    public void queryJobHandler() throws Exception {
        long jobId = XxlJobHelper.getJobId();
        String jobParam = XxlJobHelper.getJobParam();
        JSONObject jsonObj = JSONObject.parseObject(jobParam);
        JSONObject jobJson = jsonObj.getJSONObject("job");

        JSONObject content = jobJson.getJSONArray("content")
                .getJSONObject(0);

        JSONObject reader = content.getJSONObject("reader");
        JSONObject rParameter = reader.getJSONObject("parameter");
        String rUsername = rParameter.getString("username");
        String rPassword = rParameter.getString("password");

        JSONObject rConnection = rParameter.getJSONArray("connection")
                .getJSONObject(0);


        String jdbcUrl = rConnection.getString("jdbcUrl");
        String querySql = rConnection.getString("querySql");
        String splitPk = rParameter.getString("splitPk");
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 建立数据库连接
            connection = DriverManager.getConnection(jdbcUrl, rUsername, rPassword);
            // 创建 Statement 对象
            statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            // 执行查询
            resultSet = statement.executeQuery(querySql);
            int columnCount = resultSet.getMetaData().getColumnCount();
            // 逐行处理查询结果
            Object maxPkValue = null;
            while (resultSet.next()) {
                JSONObject jsonObject = new JSONObject();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSet.getMetaData().getColumnName(i);
                    Object value = resultSet.getObject(i);
                    if (value instanceof String) {
                        value = StrUtil.trim((String) value);
                    }
                    jsonObject.put(columnName, value);
                }
                if (StrUtil.isNotBlank(splitPk)) {
                    Object splitPkValue = jsonObject.get(splitPk);
                    maxPkValue = gatMax(maxPkValue, splitPkValue);
                }
            }

            System.out.println("-------------" + maxPkValue + "------>" + DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            DbUtil.close(resultSet, statement, connection);
        }
    }


    public Object gatMax(Object aObject, Object bObject) {
        boolean okClass = bObject instanceof LocalDateTime || bObject instanceof Date || bObject instanceof Long || bObject instanceof Integer;
        if (!okClass) {
            throw new RuntimeException("splitPk 不支持的数据类型");
        }
        if (aObject == null) return bObject;
        if (aObject instanceof LocalDateTime) {
            LocalDateTime v1 = Convert.toLocalDateTime(aObject);
            LocalDateTime v2 = Convert.toLocalDateTime(bObject);
            if (ObjUtil.compare(v1, v2) < 0) {
                return v2;
            }
        } else if (aObject instanceof Date) {
            Date v1 = Convert.toDate(aObject);
            Date v2 = Convert.toDate(bObject);
            if (ObjUtil.compare(v1, v2) < 0) {
                return v2;
            }
        } else if (aObject instanceof Long) {
            Long v1 = Convert.toLong(aObject);
            Long v2 = Convert.toLong(bObject);
            if (ObjUtil.compare(v1, v2) < 0) {
                return v2;
            }
        } else if (aObject instanceof Integer) {
            Integer v1 = Convert.toInt(aObject);
            Integer v2 = Convert.toInt(bObject);
            if (ObjUtil.compare(v1, v2) < 0) {
                return v2;
            }
        }
        return aObject;
    }


}
